package com.bigfans.catalogservice.service.spec;

import com.bigfans.catalogservice.dao.SpecOptionDAO;
import com.bigfans.catalogservice.model.SpecOption;
import com.bigfans.catalogservice.model.SpecValue;
import com.bigfans.catalogservice.service.category.CategoryService;
import com.bigfans.framework.dao.BaseServiceImpl;
import com.bigfans.framework.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @Description:
 * @author lichong 2015年5月30日下午10:53:15
 *
 */
@Service(SpecOptionServiceImpl.BEAN_NAME)
public class SpecOptionServiceImpl extends BaseServiceImpl<SpecOption> implements SpecOptionService {

	public static final String BEAN_NAME = "specOptionService";

	@Autowired
	private SpecOptionDAO specOptionDAO;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private SpecValueService specValueService;
	
	@Autowired
	public SpecOptionServiceImpl(SpecOptionDAO specDAO) {
		super(specDAO);
	}

	@Transactional
	@Override
	public void create(SpecOption spec) throws Exception {
		super.create(spec);
		List<String> values = spec.getValues();
		if(CollectionUtils.isNotEmpty(values)){
			List<SpecValue> valueList = new ArrayList<SpecValue>();
			for (String val : values) {
				SpecValue specValue = new SpecValue();
				specValue.setOptionId(spec.getId());
				specValue.setCategoryId(spec.getCategoryId());
				specValue.setValue(val);
				valueList.add(specValue);
			}
			specValueService.batchCreate(valueList);
		}
	}

	@Override
	@Transactional(readOnly = true)
	public List<SpecOption> listByPid(String pid, Long start , Long pagesize) throws Exception {
		List<SpecOption> options = specOptionDAO.listByPid(pid , start , pagesize);
		if(options!= null){
			for (SpecOption item : options) {
				List<SpecValue> valueList = specValueService.listByOptionId(item.getId());
				item.setSpecValues(valueList);
			}
		}
		return specOptionDAO.listByPid(pid , start , pagesize);
	}

	@Override
	@Transactional(readOnly = true)
	public List<SpecOption> listByPgId(String pgId, Long start , Long pagesize) throws Exception {
		return specOptionDAO.listByPgId(pgId, start , pagesize);
	}

	@Override
	@Transactional(readOnly = true)
	public List<SpecOption> listByCatId(String catId, Long start , Long pagesize) throws Exception {
		List<String> parentIds = categoryService.listParentIds(catId);
		parentIds.add(catId);
		List<SpecOption> options = specOptionDAO.listByCatIds(parentIds , start , pagesize);
		if(options!= null){
			for (SpecOption item : options) {
				if(item.getInputType().equals(SpecOption.INPUTTYPE_SELECT)){
					List<SpecValue> valueList = specValueService.listByOptionId(item.getId());
					item.setSpecValues(valueList);
				}
			}
		}
		return options;
	}

}
